import React, { Component } from 'react';
import PropTypes from 'prop-types';

import styles from './ChartTextLabel.less';
import { subscribeComp } from '@/services/bajaService';

class ChartTextLabel extends Component {

  static defaultProps = {
    title: '',
    fontSize: '16px',
    unit: 'KWH'
  }

  constructor(props) {
    super(props);
    this.state = {value: ''};
    this.sub = null;
  }

  updateChart = (value) => {
    this.setState({ value });
  }

  subscribeChart = () => {
    subscribeComp(this.props.ord, (component)=>{
      const value = parseFloat(component.getOut().getValue().toFixed(2));
      this.updateChart(value);
    }).then((sub)=> {
      this.sub = sub;
    });
  }

  componentDidMount() {
    this.subscribeChart();
  }

  componentWillUnmount() {
    if(this.sub && this.sub.unsubscribeAll) {
      this.sub.unsubscribeAll();
      this.sub.detach();
    }
  }

  render() {
    const { title, fontSize, imageSrc, unit } = this.props;
    const { value } = this.state;
    return (
      <div className={styles.frame}>
        <p className={styles.title} style={{fontSize}}>{title}</p>
        <div className={styles.chartTextLabel}>
          <div className={styles.box}>
            <div className={styles.iframe}>
              <img className={styles.img} src={imageSrc} alt="Data Label"/>
              <div className={styles.unit} style={{fontSize}}><span>{value}</span> {unit}</div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

ChartTextLabel.propTypes = {
  ord: PropTypes.string.isRequired,
  title: PropTypes.string,
  fontSize: PropTypes.string,
  imageSrc: PropTypes.string.isRequired,
  unit: PropTypes.string
}


export default ChartTextLabel;
